package cn.edu.zjut.medlinebackend.controller;

import cn.edu.zjut.medlinebackend.mapper.*;
import cn.edu.zjut.medlinebackend.model.*;
import cn.edu.zjut.medlinebackend.service.GroupService;
import cn.edu.zjut.medlinebackend.utils.MyUtils;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/page")
public class PageController {
    @Resource
    private PostMapper postMapper;
    @Resource
    private UserMapper userMapper;

    @Resource
    private FavoriteMapper favoriteMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private MembersMapper membersMapper;

    @Resource
    private GroupfileMapper groupFileMapper;


    @RequestMapping("/toSearchPage")
    public String toSearchPage() {
        return "search";
    }

    @RequestMapping("/toLoginPage")
    public String toLoginPage() {
        return "user/login";
    }

    @RequestMapping("/toRegisterPage")
    public String toRegisterPage() {
        return "user/register";
    }

    @RequestMapping("/toGroupPage")
    public String toGroupPage(HttpServletRequest request, Model model) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")) {
                    model.addAttribute("username", cookie.getValue());
                    break;
                }
            }
        }
        return "group";
    }

    @RequestMapping("/toChatRoomPage")
    public String toChatRoomPage(HttpServletRequest request, Model model) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")) {
                    model.addAttribute("username", cookie.getValue());
                    break;
                }
            }
        }
        return "chatroom";
    }

    @RequestMapping("/toDataPage")
    public String toDataPage(HttpServletRequest request,Model model){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")) {
                    model.addAttribute("username", cookie.getValue());
                    break;
                }
            }
        }
        List<Post> posts=postMapper.getAll();
        List<Post> postList=new ArrayList<>();
        for (Post item:posts) {
            Post newpost=new Post();
            newpost.setDislikenum(item.getDislikenum());
            newpost.setThumbnum(item.getThumbnum());
            newpost.setDownloadnum(item.getDownloadnum());
            newpost.setTitle(item.getTitle());
            postList.add(newpost);
        }
        model.addAttribute("Posts", JSON.toJSONString(postList));
        return "echartsData";
    }

    @RequestMapping("/toUserCenterPage")
    public String showUserInfo(HttpServletRequest request, Model model) {
        Cookie[] cookies = request.getCookies();
        String username = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")) {
                    username = cookie.getValue();
                    model.addAttribute("userInfo", cookie.getValue());
                    break;
                }
            }
        }

        //从files文件夹中读取
//        String folderPath = FILE_ROOT_PATH;  // 文件夹路径
//        File folder = new File(folderPath);
//        File[] files = folder.listFiles();
//        List<String> fileName = FileUtil.listFileNames(String.valueOf(folder)); // 使用Hutool获取文件名列表


        // 用户不存在，跳转到到登录页
        if (username == null || username.isEmpty()) {
            System.out.println("用户未登陆，请先登录再来查看");
            return "user/login";
        }

        User byUsername = userMapper.getUserByUsername(username);

        if (byUsername == null) {
            System.out.println("用户不存在");
            return null;
        }

        // 从数据库中读取文件名
        List<Post> postList = postMapper.getAllByUserid(byUsername.getId());
        List<String> fileNames = new ArrayList<>();
        postList.forEach(post -> fileNames.add(post.getTitle()));
        model.addAttribute("uploadedFils", fileNames);

        List<Favorite> favoritesList = favoriteMapper.getAllByUserid(byUsername.getId());
        List<String> favoritesFileNames = new ArrayList<>();
        favoritesList.forEach(favorites -> favoritesFileNames.add(favorites.getFileName()));
        model.addAttribute("favoriteFiles", favoritesFileNames);

        return "user/userCenter";
    }
    @RequestMapping("/toAdminCenterPage")
    public String showAdminnfo(HttpServletRequest request, Model model) {
        Cookie[] cookies = request.getCookies();
        String username = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")) {
                    username = cookie.getValue();
                    model.addAttribute("userInfo", cookie.getValue());
                    break;
                }
            }
        }

        //从files文件夹中读取
//        String folderPath = FILE_ROOT_PATH;  // 文件夹路径
//        File folder = new File(folderPath);
//        File[] files = folder.listFiles();
//        List<String> fileName = FileUtil.listFileNames(String.valueOf(folder)); // 使用Hutool获取文件名列表


        // 用户不存在，跳转到到登录页
        if(username == null || username.isEmpty()){
            System.out.println("用户未登陆，请先登录再来查看");
            return "user/login";
        }

        User byUsername = userMapper.getUserByUsername(username);

        if(byUsername == null){
            System.out.println("用户不存在");
            return null;
        }

        // 从数据库中读取文件名
        List<Post> postList = postMapper.getAllByUserid(byUsername.getId());
        List<String> fileNames = new ArrayList<>();
        postList.forEach(post -> fileNames.add(post.getTitle()));
        model.addAttribute("uploadedFils", fileNames);

        List<Favorite> favoritesList = favoriteMapper.getAllByUserid(byUsername.getId());
        List<String> favoritesFileNames = new ArrayList<>();
        favoritesList.forEach(favorites -> favoritesFileNames.add(favorites.getFileName()));
        model.addAttribute("favoriteFiles", favoritesFileNames);

        return "user/adminCenter";
    }
    @RequestMapping("/toCreateUserPage")
    public String toCreateUserPage() {
        return "user/createUser";
    }

    private static final String FILE_ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    @RequestMapping("/toFilePage")
    public String toFilePage(Model model) {
        String folderPath = FILE_ROOT_PATH;  // 文件夹路径
        File folder = new File(folderPath);
        File[] files = folder.listFiles();
        List<String> fileName = FileUtil.listFileNames(String.valueOf(folder)); // 使用Hutool获取文件名列表
        model.addAttribute("uploadedFils", fileName);
        return "file";// 这里的 "file" 是你的JSP页面文件名
    }

    @RequestMapping("/toAnswerPage")
    public String toAnswerPage() {
        return "answer";
    }

    @RequestMapping("/Exit")
    public String exitPage(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            // 手动销毁session对象
            session.invalidate();
            // 销毁cookie（退出系统将所有的cookie全部销毁）
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        return "redirect:/";
    }

    @RequestMapping("/toNotificationPage")
    public String toNotificationPage() {
        return "notification";
    }

    @RequestMapping("/toGroupDetail")
    public String toGroupDetail(String groupId, HttpServletRequest request) {
        // 展示小组成员和小组中共享的文件   自己上传的文件
        request.setAttribute("groupId", groupId);
        Group group = groupMapper.selectById(groupId);


        // 获取到了每个成员的名字
        List<Members> members = membersMapper.getMembers(group.getGroupname());
        List<String> memberNames = members.stream()
                .map(Members::getUsername)
                .collect(Collectors.toList());
        request.setAttribute("memberNames", memberNames);

        // 获取小组中共享的文件
        QueryWrapper<Groupfile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("groupId", groupId);
        List<Groupfile> groupFiles = groupFileMapper.selectList(queryWrapper);
        request.setAttribute("groupFiles", groupFiles);

        // 获取自己共享的文件
        String username = MyUtils.getCookieValue(request, "username");
        System.out.println(username);
        User byUsername = userMapper.getUserByUsername(username);
        List<String> myShareFileNames = new ArrayList<>();
        groupFiles.forEach(groupfile ->{
            if(groupfile.getUserid()==byUsername.getId())
                myShareFileNames.add(groupfile.getFilename());
        });
        request.setAttribute("myShareFileNames", myShareFileNames);

        // 获取自己上传的文件
        List<Post> postList = postMapper.getAllByUserid(byUsername.getId());
        List<String> fileNames = new ArrayList<>();
        postList.forEach(post -> fileNames.add(post.getTitle()));
        request.setAttribute("uploadedFils", fileNames);

        return "group_detail";
    }
}
